package bTree.LeetCode;

import bTree.bTree;

import javax.swing.tree.TreeNode;
import java.util.LinkedList;
import java.util.Queue;

public class 填充每个节点的下一个右侧节点指针2 {
    public Node connect(Node root) {
        if(root==null){
            return root;
        }
        bfs(root);
        return root;
    }
    private void bfs(Node root) {
        Queue<Node>queue=new LinkedList<Node>();
        queue.add(root);
        while (!queue.isEmpty()){
            int len=queue.size();
            for (int i = 0; i < len; i++) {
                if(queue.peek().left!=null){
                    queue.add(queue.peek().left);
                }
                if(queue.peek().right!=null){
                    queue.add(queue.peek().right);
                }
                Node poll = queue.poll();
                if(i==len-1){
                    poll.next=null;
                }else {
                    poll.next=queue.peek();
                }
            }
        }
    }
}